from python.coin.tool.strat_monitor.util.monitor_util import get_active_strategy
from xunkemgmt_client.client.util.query_util import (
  query_exchange_apis, query_strategies, query_accounts, query_applications)

from influxdb_client import InfluxDBClient, Point, WritePrecision  #pip install influxdb_client
from influxdb_client.client.write_api import ASYNCHRONOUS, SYNCHRONOUS
import datetime
import json

_token = "d37FqY39jpcxuSmthcMjmBnbCsWiwxk0yjpkLPjWzIANgY7ro5iNpuN-Hwcg3JObKFJpPPIBWito_yLVt4hkWA=="
_org = "order"
_bucket = "ogre_order"
_url = "http://35.79.11.23:8086"
_name = "open_order"
                                                  
class InfluxdbTakeOut:
  def __init__(self, *, url=_url, token=_token, org=_org, bucket):
    self._org = org
    self._bucket = bucket
    self._client = InfluxDBClient(url=url, token=token, org=org)

  def __query(self, query):
    tables = self._client.query_api().query(query, org=self._org)
    js = tables.to_json()
    js = json.loads(js)
    return js

class InfluxdbOutPut:
  def __init__(self, *, url=_url, token=_token, org=_org, bucket=_bucket, name=_name):
    assert(isinstance(bucket, str))
    assert(isinstance(org, str))
    self._bucket = bucket
    self._org = org
    self._name = name
    with InfluxDBClient(url=url, token=token, org=org) as client:
      self._write_api = client.write_api(write_options=SYNCHRONOUS, error_callback=self.error)

  def error(conf, data: str, exception):
    print(f"Cannot write batch: {conf}, data: {data} due: {exception}")
    

  def write_data_spot(self, tag:dict, filed:dict, ts):
    point = Point(self._name)
    for k,v in tag.items():
      point.tag(k, v)
    for k,v in filed.items():
      point.field(k, v)
    print(tag, filed)

    point.time(ts, WritePrecision.NS)
    self._write_api.write(self._bucket, self._org, point)
    self._write_api.flush()

  def __del__(self):
    self._write_api.close()


class InfluxdbTakeOut:
  def __init__(self, *, url=_url, token=_token, org=_org, bucket):
    self._org = org
    self._bucket = bucket
    self._client = InfluxDBClient(url=url, token=token, org=org)

  def __query(self, query):
    tables = self._client.query_api().query(query, org=self._org)
    js = tables.to_json()
    js = json.loads(js)
    return js


def get_real_time_info():
  strat_list = get_active_strategy()
  df_acct = query_applications()
  strat_info_list = []
  for strat in strat_list:
    acct = df_acct.loc[df_acct['strategy_name'].str.match(strat)]
    for _, row_acct in acct.iterrows():
      strat_info_list.append(row_acct)

  return strat_info_list

strategy_info =  get_real_time_info()
output = InfluxdbOutPut(name = "strategy_info")

for item in strategy_info:
  strategy = item.to_dict()
  tag = dict()
  tag['market_type'] = strategy["market_type_strat"]
  tag['exchange'] = strategy["exchange_strat"]
  tag['owner'] = strategy["owner_strat"]
  tag['account_group'] = strategy["account_group"]
  tag['business_unit'] = strategy["business_unit_acct"]
  tag['api_version'] = strategy["api_version"]
  tag['strategy_group'] = strategy["strategy_group"]
  tag['trader'] = strategy["trader"]
  tag['strategy_name'] = strategy["strategy_name"]
  if strategy["active_acct"] == True:
    tag['active'] = "True"
  else:
    tag['active'] = "False"
  
  filed = dict()
  filed["application_id"] = strategy["application_id"]
  filed["strategy_id"] = strategy["strategy_id"]
  filed["account_id"] = strategy["account_id"]
  filed["exchange_api_id"] = strategy["exchange_api_id"]

  output.write_data_spot(tag, filed, datetime.datetime.utcnow())
